package cn.naughtior.shch.utils;

import cn.naughtior.shch.consumer.Consumer;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class UserAccountInitialHandler {
	private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(UserAccountInitialHandler.class);

	protected Consumer consumer;

	public Consumer getConsumer() {
		return consumer;
	}

	public void setConsumer(Consumer consumer) {
		this.consumer = consumer;
	}

	private static ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r, "UserAccountInitial_thread");
		}
	});

	public UserAccountInitialHandler() {
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				try {
					List<Message> messages = new ArrayList<Message>();
					if(consumer == null){
						Thread.sleep(1000);
					}
					while(true) {
						try {
							messages = consumer.getMessagesWithNoAutoAck(10);
							for (Message message : messages) {
								String messageStr = null ;
								try {
									messageStr = new String(message.getResponse().getBody());
									UserMq userMq = JSONUtil.parse(messageStr,UserMq.class);
									System.out.println(userMq.getUserId());
									message.getChannel().basicAck(message.getResponse().getEnvelope().getDeliveryTag(), false);
								} catch(Exception e){
									Logger.error("UserAccountInitialHandler error" + e.getMessage(), e);
									try {
										message.getChannel().basicNack(message.getResponse().getEnvelope().getDeliveryTag(), false, true);
									} catch (IOException e1) {
										Logger.error("UserAccountInitialHandler basicNack error" + e.getMessage(),e);
									}
								}
							}
							if(messages.size() == 0){
								System.out.println("---------------empty-------------");
								Thread.sleep(1000);
							}
						} catch(Exception e){
							Logger.warn("UserAccountInitialHandler error " + e.getMessage(), e);
						}
					}
				} catch (Exception e) {
					Logger.warn("UserAccountInitialHandler exit");
				}
			}
		});
	}

	public static void shutdown(){
		executorService.shutdown();
	}


}
